<!-- 管理用户选择器 -->
<script setup>
import {Close, OfficeBuilding, Operation} from '@element-plus/icons-vue'
import { ref, watch} from "vue"
import {list as sysUserList, listSysUserSelectorData} from '@/api/system/sysUser.js'

const props = defineProps({
  selectedIds: {
    type: Array,
    default: () => []
  },
  visible: {
    type: Boolean,
    default: false
  },
  multi: {
    type: Boolean,
    default: false
  }
})

const search = ref({
  nickname: '',
  orgId: 0
})
const selectorData = ref([
  {id: 1, name: '琛贝科技有限公司', type: 1, checked: false},
  {id: 2, name: '张三', type: 2, checked: false},
  {id: 3, name: '李四', type: 2, checked: false},
  {id: 4, name: '王五', type: 2, checked: false},
  {id: 5, name: '赵六', type: 2, checked: false},
  {id: 6, name: '刘备', type: 2, checked: false},
  {id: 7, name: '关羽', type: 2, checked: false},
  {id: 8, name: '张飞', type: 2, checked: false},
  {id: 9, name: '诸葛亮', type: 2, checked: false},
  {id: 10, name: '赵云', type: 2, checked: false}
])
const selectedData = ref([])

const emit = defineEmits(['update:visible'])

const dialogVisible = ref(false)

//导航数据
const navData = ref([
  {id: 0, name: '根组织'},
])

watch(() => props.visible, (newVal) => {
  if (newVal) {
    dialogVisible.value = true

    search.value = {
      orgId: 0,
      nickname: ''
    }

    listSysUserSelectorData(search.value).then((resp) => {
      let respData = resp.data
      if (props.selectedIds) {
        sysUserList({ids: props.selectedIds}).then(resp => {
          const sysUsers = resp.data
          if (sysUsers) {
            selectedData.value = sysUsers.map(sysUser => ({
              id: sysUser.id,
              name: sysUser.nickname,
              icon: sysUser.avatar,
              type: 2
            }))
          }

          selectorData.value = nodeDataConvertSelectorData(respData, selectedData.value)
        })
      }
    })
  } else {
    dialogVisible.value = false
  }
}, { immediate: true })

//取消
const onCancel = () => {
  emit('update:visible', false)
}

//确定
const onConfirm = () => {
  emit('select', selectedData.value)
}

//移除
const remove = (item) => {
  const selectedDataIndex = selectedData.value.findIndex(item1 => item1.id === item.id)
  if (selectedDataIndex !== -1) {
    selectedData.value.splice(selectedDataIndex, 1)
  }

  const index = selectorData.value.findIndex(item1=> item1.id === item.id)
  if (index !== -1) {
    selectorData.value[index].checked = false
  }
}

//清空
const removeAll = () => {
  const unSelectedIdArr = selectedData.value.map(item => item.id)
  selectedData.value.splice(0, selectedData.value.length)
  unSelectedIdArr.forEach(id => {
    const index = selectorData.value.findIndex(item => item.id === id)
    if (index !== -1) {
      selectorData.value[index].checked = false
    }
  })
}

//监听Checkbox变化事件
const onCheckboxChange = (event, item) => {
  if (event) {
    if (props.multi) {
      selectedData.value.push({...item})
    } else {
      if (selectedData.value.length > 0) {
        const index = selectorData.value.findIndex(item1=> item1.id === selectedData.value[0].id)
        if (index !== -1) {
          selectorData.value[index].checked = false
        }
      }
      selectedData.value[0] = item
    }
  } else {
    const index = selectedData.value.findIndex(item1 => item1.id === item.id)
    if (index !== -1) {
      selectedData.value.splice(index, 1)
    }
  }
}

//重置工作
const dialogClose = () => {
  selectorData.value = [
    {id: 1, name: '琛贝科技有限公司', type: 1, checked: false},
    {id: 2, name: '张三', type: 2, checked: false},
    {id: 3, name: '李四', type: 2, checked: false},
    {id: 4, name: '王五', type: 2, checked: false},
    {id: 5, name: '赵六', type: 2, checked: false},
    {id: 6, name: '刘备', type: 2, checked: false},
    {id: 7, name: '关羽', type: 2, checked: false},
    {id: 8, name: '张飞', type: 2, checked: false},
    {id: 9, name: '诸葛亮', type: 2, checked: false},
    {id: 10, name: '赵云', type: 2, checked: false}
  ]
  selectedData.value = []
  navData.value = [
    {id: 0, name: '根组织'}
  ]
  emit('update:visible', false)
}

/**
 * 下级
 * @param item
 */
const subNode = (item) => {
  //新增导航信息
  navData.value.push({
    id: item.id,
    name: item.name
  })

  listSysUserSelectorData({orgId: item.id, name: ''}).then((resp) => {
    selectorData.value = nodeDataConvertSelectorData(resp.data, selectedData.value)
  })
}

/**
 * 节点数据转换成选择项数据
 * @param nodeData 响应的节点数据
 * @param selectedData 已选择的数据集合
 */
const nodeDataConvertSelectorData = (nodeData, selectedData) => {
  let selectorData = []
  if (nodeData) {
    nodeData.forEach((item) => {
      if (item.type === 1) {
        selectorData.push({id: item.id, name: item.name, type: 1, checked: false})
      } else {
        if (selectedData.length > 0) {
          let findIndex = selectedData.findIndex(item1 => item1.id === item.id)
          if (findIndex !== -1) {
            selectorData.push({id: item.id, name: item.name, type: item.type, checked: true})
          } else {
            selectorData.push({id: item.id, name: item.name, type: item.type, checked: false})
          }
        } else {
          selectorData.push({id: item.id, name: item.name, type: item.type, checked: false})
        }
      }
    })
  }

  return selectorData
}

/**
 * 监听导航栏事件
 * @param item
 * @param itemIndex
 */
const onNav = (item, itemIndex) => {
  navData.value.splice(itemIndex+1, 0)
  listSysUserSelectorData({orgId: item.id, name: ''}).then(resp => {
    selectorData.value = nodeDataConvertSelectorData(resp.data, selectedData.value)
  })
}

</script>

<template>
  <el-dialog v-model="dialogVisible" title="用户选择" width="580px" :close-on-click-modal="false" @close="dialogClose">
    <div class="sys-user-selector-main">
      <div class="left">
        <div class="left-nav-box">
          <div class="nav-item" v-for="(item, index) in navData" :key="index">
            <div :class="{active: index < navData.length - 1, 'not-active': index === navData.length - 1}" @click="onNav(item, index)">{{ item.name }}</div>
            <div class="separator" v-if="index <= (navData.length-2)">/</div>
          </div>
        </div>
        <div class="left-tool-box">
          <el-input prefix-icon="Search" v-model="search.nickname" placeholder="请输入用户名" clearable  />
        </div>
        <div class="left-main">
          <div class="item-list">
            <div class="item" v-for="(item, index) in selectorData" :key="index">
              <div>
                <el-checkbox v-model="item.checked" :disabled="item.type === 1" @change="(event) => onCheckboxChange(event, item)">
                  <template #default>
                    <div style="display: flex; flex-direction: row; align-items: center">
                      <div>
                        <el-icon size="18" v-if="item.type === 1"><OfficeBuilding /></el-icon>
                        <el-avatar :size="32" v-if="item.type === 2" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
                      </div>
                      <div style="margin-left: 8px">{{item.name}}</div>
                    </div>
                  </template>
                </el-checkbox>
              </div>
              <div class="sub-node" v-show="item.type === 1" @click="subNode(item)"><el-icon size="16"><Operation /></el-icon>下级</div>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="tool-box">
          <div>已选择{{selectedData.length}}项</div>
          <div><el-button link type="danger" @click="removeAll">清空</el-button></div>
        </div>
        <div class="selected-list">
          <div class="item" v-for="(item, index) in selectedData" :key="index">
            <div class="user-info">
              <div><el-avatar :size="32" :src="item.icon || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" /></div>
              <div class="name">{{ item.name }}</div>
            </div>
            <div class="user-remove">
              <el-icon @click="remove(item)"><Close /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.sys-user-selector-main {
  width: 100%;
  height: 380px;
  display: flex;
  flex-direction: row;
  border: 1px solid $cb-border-color;

  .left, .right {
    flex-grow: 0;
    flex-shrink: 0;
    flex-basis: 50%;
    box-sizing: border-box;
  }

  .left {
    display: flex;
    flex-direction: column;
    border-right: 1px solid $cb-border-color;
    padding: $cb-padding-value-8;
    overflow: hidden;

    .left-nav-box {
      height: 65px;
      display: flex;
      flex-direction: row;
      overflow-x: auto;
      white-space: nowrap;
      padding-bottom: $cb-padding-value-8;

      .nav-item {
        display: flex;
        flex-direction: row;
        align-items: center;
        color: $cb-color-primary;

        .active {
          cursor: pointer;
        }

        .not-active {
          color: $cb-color-info;
          cursor: default;
        }

        .separator {
          padding: 0 $cb-padding-value-8;
          color: $cb-color-info;
        }
      }
    }

    .left-main {
      flex-grow: 1;
      overflow: auto;

      .item-list {
        .item {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          padding: $cb-padding-value-8;

          &:hover {
            background: $cb-color-primary-light;
          }

          .sub-node {
            color: $cb-color-primary;
            display: flex;
            flex-direction: row;
            align-items: center;
            cursor: pointer;
          }
        }
      }
    }
  }

  .right {
    display: flex;
    flex-direction: column;

    .tool-box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding: 9px;
      border-bottom: 1px solid $cb-border-color;
    }

    .selected-list {
      display: flex;
      flex-direction: column;
      padding: $cb-padding-value-8;
      overflow: auto;
      flex-grow: 1;

      .item {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: $cb-padding-value-8;

        &:hover {
          background: $cb-color-primary-light;
        }

        .user-info {
          display: flex;
          flex-direction: row;
          align-items: center;

          .name {
            margin-left: $cb-margin-value-8;
          }
        }

        .user-remove {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
